/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import path from 'path';

import { hvigorCore, Project, FileSet, TaskInputValue } from '@ohos/hvigor';

import { ProjectPathInfoIml } from '../common/iml/project-path-info-iml.js';
import { CommonConst } from '../const/common-const.js';
import { SignTypeEnum } from '../enum/sign-type-enum.js';
import { ProjectBuildProfile } from '../options/build/project-build-profile.js';
import { FileUtil } from '../utils/file-util.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';
import { TaskNames } from './common/task-names.js';
import { PackageApp } from './package-app.js';
import { ProjectTaskService } from './service/project-task-service.js';
import { SignModel } from './sign/command-builder-impl/sign-model.js';
import { SignUtil } from './sign/sign-util.js';
import { OhosAppTask } from './task/ohos-app-task.js';

import SigningConfigBuildOpt = ProjectBuildProfile.SigningConfigBuildOpt;

/**
 * 对app包进行签名
 *
 * @since 2022/1/22
 */
export class SignApp extends OhosAppTask {
  private readonly log: OhosLogger = OhosLogger.getLoggerWithDurationId(SignApp.name, this.durationEvent.getId());
  private pathInfo: ProjectPathInfoIml;
  private signUtil: SignUtil | undefined;
  private signingConfig: SigningConfigBuildOpt | undefined;

  constructor(project: Project, taskService: ProjectTaskService) {
    super(project, taskService, TaskNames.CommonTask.SIGN_APP);
    this.pathInfo = this.service.getPathInfo();
  }

  async beforeAlwaysAction() {
    this.signUtil = new SignUtil(this.service, SignTypeEnum.APP, this.pathInfo, this.service.getTargetProduct(), this.service.getSdkInfo());
    this.signingConfig = this.signUtil._signingConfig;
    this.log.debug('signingConfigName of signApp is : ', this.signUtil._signingConfig?.name);
    this.log.warn(this.signUtil._signingConfigCheckLogStr);
  }

  declareInputs(): Map<string, TaskInputValue> {
    return SignUtil.getSigningConfigInputs(this.service.getSdkInfo(), this.signingConfig!);
  }

  declareInputFiles(): FileSet {
    if (this.signUtil) {
      return this.signUtil
        .getSigningConfigInputFiles()
        .addEntry(path.resolve(this.pathInfo.getProjectOutputPath(), this.service.getAppOutputFileName()!)!, { isDirectory: false });
    }
    return super.declareInputFiles();
  }

  declareOutputFiles(): FileSet {
    const outputFile = path.resolve(this.pathInfo.getProjectOutputPath(), this.service.getAppOutputFileName(true));
    if (outputFile) {
      return super.declareOutputFiles().addEntry(outputFile, { isDirectory: false });
    }
    return super.declareOutputFiles();
  }

  protected async doTaskAction(): Promise<void> {
    const outputFile = path.resolve(this.pathInfo.getProjectOutputPath(), this.service.getAppOutputFileName(true));
    const signModel = new SignModel(SignTypeEnum.APP, path.resolve(this.pathInfo.getProjectOutputPath(), this.service.getAppOutputFileName()!)!, outputFile!);

    // 当任务非增量时，先删除上一次已签名的输出文件
    FileUtil.deleteFile(signModel.getOutPutFilePath());
    if (!hvigorCore.getParameter().getProperty(CommonConst.ENABLE_SIGN_TASK)) {
      return;
    }
    await this.signUtil!.sign(signModel, this.durationEvent);
  }

  initTaskDepends() {
    this.dependsOn(PackageApp.name);
  }
}
